package com.dzu.easy;

import com.dzu.common.ListNode;

import java.util.HashMap;

/**
 * @author ZhaoDong
 * @date 2022/6/6 10:29
 * @description 83. 删除排序链表中的重复元素
 * <p>
 * 给定一个已排序的链表的头 head ， 删除所有重复的元素，使每个元素只出现一次 。返回 已排序的链表 。
 * <p>
 * 输入：head = [1,1,2]
 * 输出：[1,2]
 */
public class Test83 {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode31 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode31;
        ListNode listNode = deleteDuplicates(listNode1);
        System.out.println(listNode);

    }

    // 2ms
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode root = head;
        HashMap<Integer, ListNode> map = new HashMap<>();
        while (head != null) {
            if (map.containsKey(head.val)) {
                ListNode listNode = map.get(head.val);
                listNode.next = head.next;
            } else {
                map.put(head.val, head);
            }
            head = head.next;
        }

        return root;
    }

    //0ms
    public static ListNode deleteDuplicates2(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.val == cur.next.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}
